// Includes 
#include "SerialLCD.h"
#include "SoftwareSerial.h" //this is a must
#include "DHT.h"
#include "SPI.h"
#include "Ethernet.h"

// Define
#define DHTPIN 2                      // what pin we're connected to
#define DHTTYPE DHT11                 // DHT 11 
#define REFRESH_DELAY 5               // Délai de rafraichissement
#define STANBY_BACKLIGHT_DELAY 10     // Délais pour éteindre le rétro éclairage
#define DELAY_WS_CALL 60              // Appel le webservice tous les 60s
#define LCD_PIN_1 4                   // Branchement du LCD
#define LCD_PIN_2 5

// Déclarations
SerialLCD slcd(LCD_PIN_1,LCD_PIN_2);
DHT       dht(DHTPIN, DHTTYPE);

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 24 };
byte ip_dns[] = { 8,8,8,8 };
byte gateway[] = { 192, 168, 1, 1 };
IPAddress server(192,168,1,26);
EthernetClient client;
int standby = 0;
int last_call_ws = 0;

void setup() {

  Serial.begin(9600); 

  dht.begin();
  slcd.begin();
  Ethernet.begin(mac, ip, ip_dns, gateway);
  delay(1000);  // Initalisation 

  // Affichage de base de l'écran
  slcd.setCursor(0, 0);
  slcd.print("Temp  :");
  slcd.setCursor(10, 0);
  slcd.print("C");
  slcd.setCursor(0, 1);
  slcd.print("Humid : ");
  slcd.setCursor(10, 1);
  slcd.print('%');
  slcd.backlight();

}

void loop() {

  // Lit la temperature et l'hulidité
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  Serial.println(h);
  Serial.println(t);
  
  // Affiche les résultats sur l'écran
  slcd.setCursor(8, 0);
  slcd.print(t, 10);
  slcd.setCursor(8, 1);
  slcd.print(h,10);

  if(last_call_ws == 60){
    // Envoi les résultats aux ws
    if (client.connect(server, 80)) {
      Serial.println("connected");
      int int_temperature = (int) t;
      String url = "GET /Domotique/api/feed/temperature/";
      url = url + int_temperature;
      url = url + " HTTP/1.0"; 
      client.println(url);
      client.println();
      client.stop();
    }else{
      Serial.println("not connected");
    }
    last_call_ws = 0;
  }else{
    last_call_ws = last_call_ws + REFRESH_DELAY;
  }

  // Attends
  delay(REFRESH_DELAY * 1000);

  // étein le retro-eclairage
  standby = standby + REFRESH_DELAY;
  if( standby >= STANBY_BACKLIGHT_DELAY){
    slcd.noBacklight();
  }

}